import { Children, FC, useContext, useRef, useState } from "react";
import { MenuItemProps, SubMenuProps } from "./interface";
import classNames from "classnames";
import { MenuContext, MenuItem } from "./menu";
import React from "react";
import Icon from "../Icon/Icon";
import { CSSTransition } from 'react-transition-group';
import Transition from "../Transition/transition";

const SubMenu: FC<SubMenuProps> = (props) => {

    const { title, index, disabled, className, style, children, defaultOpenMenus } = props;

    const { index: activeIndex, onSelect } = useContext(MenuContext);

    const [opened, setOpened] = useState(defaultOpenMenus);

    const nodeRef = useRef(null);

    const classes = classNames('kd-memu-item kd-memu-item-submenu', {
        'is-disabled': disabled,
        'is-active': (index === activeIndex) && !disabled,
        'is-opened': opened,
    })

    // 功能：切换子菜单项的展开状态
    function toggleSubMenuOpenState() {
        if (onSelect && !disabled && (typeof index === 'string')) {
            onSelect(index);
        }
        setOpened(!opened);
    }

    // 功能：鼠标悬浮时，显示子菜单项
    // const hoverSubMenuOpenState = {
    //     onMouseEnter() {
    //         setOpened(true);
    //     },
    //     onMouseLeave() {
    //         setOpened(false);
    //     }
    // }

    // 在children中只渲染MenuItem组件
    const renderChildren = () => {
        const childrenComponent = Children.map(children, (child, i) => {
            // 检查：child是否为有效的React元素，以及其类型是否为MenuItem
            if (React.isValidElement(child) && child.type === MenuItem) {
                // 增加：自动为MenuItem组件的index属性赋值
                return React.cloneElement(
                    child as React.ReactElement<MenuItemProps>,
                    { index: `${index}-${i}` }
                );
                // return child;
            } else {
                console.error('Warning: SubMenu has a child which is not a MenuItem component');
            }
        })

        const classes = classNames('kd-submenu', {
            'menu-opened': opened,
        })

        return (
            // <ul className={classes} ref={nodeRef}>
            //     {childrenComponent}
            // </ul>
            <ul className={classes}>
                {childrenComponent}
            </ul>
        )
    }

    return (
        // <li className={classes} style={style}>

        //     <div className="kd-submenu-title" onClick={toggleSubMenuOpenState}>
        //         {title}
        //         <Icon icon='angle-down' className="arrow-icon" />
        //     </div>

        //     <CSSTransition
        //         in={opened}        // 控制组件是否显示
        //         timeout={300}      // 动画持续时间
        //         classNames='fade'  // CSS 类名前缀
        //         unmountOnExit      // 它会在组件离开（退出）时将其从DOM中卸载
        //         nodeRef={nodeRef}  // 传递 ref
        //     >
        //         {/* 将 ref 绑定到 DOM 元素 */}
        //         <div ref={nodeRef}> 
        //             {renderChildren()}
        //         </div>
        //     </CSSTransition>

        // </li>
        <li className={classes} style={style}>

            <div className="kd-submenu-title" onClick={toggleSubMenuOpenState}>
                {title}
                <Icon icon='angle-down' className="arrow-icon" />
            </div>

            {/* <Transition
                animation='zoom-in-top'
                in={opened}
                timeout={300}
                nodeRef={nodeRef}
            >
                <div ref={nodeRef}>
                    {renderChildren()}
                </div>
            </Transition> */}
            <Transition
                animation='zoom-in-top'
                in={opened}
                timeout={300}
            >
                {renderChildren()}
            </Transition>

        </li>
    )
}

// 完成正确的MenuItem和SubMenu中的MenuItem的Index注入功能
// TODO: 添加鼠标悬浮时，显示子菜单项的功能
// 添加mode为vertical时，子菜单项默认显示的功能
export default SubMenu;